<?php
require_once __DIR__ . '/../../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    die('您没有权限访问此页面');
}

$settlementId = intval($_GET['id'] ?? 0);

if ($settlementId <= 0) {
    die('结算记录ID无效');
}

$db = getDB();

// 获取结算信息
$stmt = $db->prepare("SELECT s.*, u.username, u.phone FROM settlements s 
                     LEFT JOIN users u ON s.user_id = u.id 
                     WHERE s.id = ?");
$stmt->execute([$settlementId]);
$settlement = $stmt->fetch();

if (!$settlement) {
    die('结算记录不存在');
}

// 处理结算截图
$currentScreenshots = [];
if (!empty($settlement['settlement_screenshots'])) {
    $screenshots = json_decode($settlement['settlement_screenshots'], true);
    if (is_array($screenshots) && !empty($screenshots)) {
        foreach ($screenshots as $screenshot) {
            if (!empty($screenshot)) {
                $currentScreenshots[] = [
                    'filename' => $screenshot,
                    'url' => UPLOAD_URL . 'settlements/' . $screenshot
                ];
            }
        }
    }
}

// 生成防重复提交token
$formToken = md5(uniqid(mt_rand(), true) . $_SERVER['REMOTE_ADDR']);
if (!isset($_SESSION['form_tokens'])) {
    $_SESSION['form_tokens'] = [];
}
$_SESSION['form_tokens'][] = $formToken;
if (count($_SESSION['form_tokens']) > 50) {
    array_shift($_SESSION['form_tokens']);
}
?>

<form method="POST" enctype="multipart/form-data" id="editSettlementForm">
    <input type="hidden" name="form_token" value="<?php echo $formToken; ?>">
    <input type="hidden" name="action" value="update_settlement_info">
    <input type="hidden" name="settlement_id" value="<?php echo $settlement['id']; ?>">
    
    <div class="mb-3">
        <label class="form-label">结算信息</label>
        <div class="card">
            <div class="card-body">
                <p><strong>结算ID：</strong> <?php echo $settlement['id']; ?></p>
                <p><strong>用户：</strong> <?php echo htmlspecialchars($settlement['username']); ?> (<?php echo htmlspecialchars($settlement['phone']); ?>)</p>
                <p><strong>总金额：</strong> <?php echo formatAmount($settlement['total_amount']); ?></p>
                <p><strong>状态：</strong> 
                    <span class="badge bg-<?php echo $settlement['status'] == 'completed' ? 'success' : 'warning'; ?>">
                        <?php echo $settlement['status'] == 'completed' ? '已结算' : '待结算'; ?>
                    </span>
                </p>
            </div>
        </div>
    </div>
    
    <div class="mb-3">
        <label for="settlement_info" class="form-label">结算备注信息</label>
        <textarea class="form-control" id="settlement_info" name="settlement_info" rows="4" placeholder="请输入结算说明、备注等"><?php echo htmlspecialchars($settlement['settlement_info'] ?? ''); ?></textarea>
    </div>
    
    <div class="mb-3">
        <label for="settlement_screenshots" class="form-label">结算截图</label>
        <input type="file" class="form-control" id="settlement_screenshots" name="settlement_screenshots[]" accept="image/*" multiple>
        <div class="form-text">支持多张图片，格式：JPG、PNG、GIF，最大 5MB/张</div>
        
        <!-- 图片预览区域 -->
        <div id="imagePreview" class="mt-2"></div>
        
        <!-- 当前截图显示 -->
        <!-- 当前截图显示 -->
        <?php if (!empty($currentScreenshots)): ?>
            <div class="mt-3">
                <label class="form-label">当前结算截图</label>
                <div class="row">
                    <?php foreach ($currentScreenshots as $screenshot): ?>
                        <div class="col-md-3 mb-3">
                            <div class="card">
                                <a href="javascript:void(0)" onclick="enlargeImage('<?php echo $screenshot['url']; ?>')">
                                    <img src="<?php echo $screenshot['url']; ?>" class="card-img-top img-enlargeable" style="height: 120px; object-fit: cover;">
                                </a>
                                <div class="card-body p-2">
                                    <button type="button" class="btn btn-sm btn-outline-danger w-100" onclick="deleteSettlementScreenshot(<?php echo $settlement['id']; ?>, '<?php echo $screenshot['filename']; ?>')">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <div class="text-end">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="submit" class="btn btn-primary" id="submitBtn">
            <i class="bi bi-save"></i> 保存修改
        </button>
    </div>
</form>

<script>
// 防止重复提交
let isSubmitting = false;

// 图片预览功能
document.getElementById('settlement_screenshots').addEventListener('change', function(e) {
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';
    
    const files = e.target.files;
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'img-thumbnail me-2 mb-2';
                img.style.maxHeight = '100px';
                preview.appendChild(img);
            };
            reader.readAsDataURL(file);
        }
    }
});

// 图片放大功能
function enlargeImage(src) {
    // 创建图片查看模态框
    const modalHtml = `
        <div class="modal fade" id="imageViewerModal" tabindex="-1">
            <div class="modal-dialog modal-xl">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">图片预览</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body text-center">
                        <img src="${src}" class="img-fluid" style="max-height: 80vh;">
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('imageViewerModal'));
    modal.show();
    
    // 清理：模态框关闭后移除
    document.getElementById('imageViewerModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

// 表单提交
document.getElementById('editSettlementForm').addEventListener('submit', function(event) {
    event.preventDefault();
    
    if (isSubmitting) {
        showToast('正在处理中，请勿重复提交', 'warning');
        return;
    }
    
    isSubmitting = true;
    const submitBtn = document.getElementById('submitBtn');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';
    
    const formData = new FormData(this);
    
    fetch('api/update_settlement_info.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('结算信息更新成功', 'success');
            // 关闭模态框并刷新页面
            const modal = bootstrap.Modal.getInstance(document.getElementById('editSettlementModal'));
            modal.hide();
            setTimeout(() => {
                location.reload();
            }, 1000);
        } else {
            showToast('更新失败: ' + data.message, 'danger');
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
            isSubmitting = false;
        }
    })
    .catch(error => {
        showToast('更新失败: ' + error.message, 'danger');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
        isSubmitting = false;
    });
});

// 删除结算截图
function deleteSettlementScreenshot(settlementId, filename) {
    if (!confirm('确定要删除这张结算截图吗？')) {
        return;
    }
    
    fetch('api/delete_settlement_screenshot.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            settlement_id: settlementId,
            filename: filename
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('截图删除成功', 'success');
            // 重新加载表单
            const modal = bootstrap.Modal.getInstance(document.getElementById('editSettlementModal'));
            modal.hide();
            showEditSettlementModal(settlementId);
        } else {
            showToast('删除失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showToast('删除失败: ' + error.message, 'danger');
    });
}
</script>